package com.atguigu.springcloud.cas;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 利用CAS unsafe 实现自旋锁
 */
public class SpinLockDemo {
    private AtomicReference<Thread> reference  = new AtomicReference<>();

    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"\t haha QAQ,等着被");
        while (!reference.compareAndSet(null, thread)){
        }
    }

    public void myUnlock(){
        Thread thread = Thread.currentThread();
        reference.compareAndSet(thread,null);
        System.out.println(thread.getName()+"\t CAS 释放");
    }

    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo demo = new SpinLockDemo();
        new Thread(() ->{
            demo.myLock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            demo.myUnlock();
        },"AA").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(() -> {
            demo.myLock();
            demo.myUnlock();
        },"BB").start();
    }
}
